﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace EmailManager
{
    public class VerifyCodeManger
    {
        public const int VerifyCodeTime = 30 * 60 * 1000;
        public static string GetEmailBody(int code) => $"{Config.ContentBefore}{code}{Config.ContentAfter}";

        public static void Register(string email)
        {
            var code = GenerateCode();
            EmailSender.SendEmail(new[] {email}, Config.Topic, GetEmailBody(code));
            if (VerifyCodeDictionary.ContainsKey(email))
            {
                VerifyCodeDictionary[email] = code;
            }
            else VerifyCodeDictionary.Add(email, code);

            new Thread(new ThreadStart(delegate
            {
                Thread.Sleep(VerifyCodeTime);
                VerifyCodeDictionary.Remove(email);
            })).Start();
        }

        public static bool Verify(string email, int code)
        {
            return VerifyCodeDictionary.ContainsKey(email) && VerifyCodeDictionary[email] == code;
        }

        public static int GenerateCode()
        {
            var rd = new Random();
            return rd.Next(100000, 999999);
        }

        private static readonly Dictionary<string, int> VerifyCodeDictionary = new Dictionary<string, int>();
    }
}